<template>
   <div style="display: flex;justify-content: center">
     <div class="left_bar" style="width: 200px;margin-top: 50px;border-right: 2px solid #ccc">
       <div class="title" style="font-size: 20px;text-align: center">题目类型</div>
       <div class="type_list" style="text-align: center;margin-top: 20px">
         <van-button plain type="primary" style="margin-bottom: 20px;cursor: pointer" @click="changeType('single')">单选题</van-button><br/>
         <van-button plain type="primary" style="margin-bottom: 20px;cursor: pointer" @click="changeType('multiple')">多选题</van-button><br/>
         <van-button plain type="primary" style="margin-bottom: 20px;cursor: pointer" @click="changeType('gap')">填空题</van-button>
       </div>
     </div>
     <div class="right" style="width: calc(100% - 300px);margin-top: 50px;padding-left: 30px">
      <div class="heard" style="font-size: 20px">
        答题时间：{{totalTime}}分钟  <span style="display: inline-block;margin-left: 30px" v-if="!study">得分为：{{grade}}分</span>
      </div>
     <div class="tip">
       <p v-if="showAnswer">第20道题，总共50题,每题为5分</p>
       <p>请认真阅读每道题目，并按照题目要求作答（已选项不可更改）</p>
     </div>
     <div class="question">
       <div class="question_content"  v-if="questionType!=='gap'">请在下列选项中选择正确的答案</div>
       <div class="question_content" v-if="questionType=='gap'">请在下列空格中填写正确答案</div>
       <div style="margin-top: 20px" class="danxuan" v-if="questionType=='single'">
         <div class="content" style="margin-bottom: 20px">{{currentQuestionsIndex+1+':'+currentQuestions[currentQuestionsIndex].content}}</div>
       <van-checkbox-group :max="1" v-model="answers[currentQuestionsIndex]">
         <van-checkbox
           v-for="(question) in currentQuestions[currentQuestionsIndex].questions"
           :key="question"
           :name="question"
         >{{question }}
         </van-checkbox>
       </van-checkbox-group>
     </div>
       <div style="margin-top: 20px" class="duoxuan" v-if="questionType=='multiple'">
         <div class="content" style="margin-bottom: 20px">{{currentQuestionsIndex+1+':'+currentQuestions[currentQuestionsIndex].content}}</div>
         <van-checkbox-group  v-model="answers[currentQuestionsIndex]">
           <van-checkbox
             v-for="(question) in currentQuestions[currentQuestionsIndex].questions"
             :key="question"
             :name="question"
           >{{question }}
           </van-checkbox>
         </van-checkbox-group>
       </div>
       <div style="margin-top: 20px" class="tiankong" v-if="questionType=='gap'">
        <div class="content" style="margin-bottom: 20px">{{currentQuestionsIndex+1+':'+currentQuestions[currentQuestionsIndex].content}}</div>
         <input type="text" v-model="answers[currentQuestionsIndex]" placeholder="请填写正确答案" style="width: 200px;height: 30px">
       </div>
     </div>
     <div class="bottom" style="margin-top: 50px">
       <van-row type="flex" justify="space-around">
         <van-button size="normal" type="primary" style="cursor: pointer" @click=" showAnswer=!showAnswer" v-if="study">查看答案解析</van-button>
         <van-button size="normal" type="primary" style="cursor: pointer" @click="submit()" v-if="!study&&questionType=='gap'&&currentQuestionsIndex==currentQuestions.length-1">提交</van-button>
         <van-button size="normal" type="primary" style="cursor: pointer" @click="next()">下一题</van-button>
       </van-row>
     </div>
     <div class="answer" v-if="showAnswer">正确答案为:{{currentQuestions[currentQuestionsIndex].answers}}</div>
   </div>
   </div>
</template>

<script>
  import {mapState} from 'vuex'
  import {baseUrl} from "../constants";
  import {QuestionBank} from "../constants";
  export default {
        name: "answerIndex",
      data () {
        return {
          showAnswer:false,//是否显示答案
          questionType:'',//题目类型
          currentQuestions:[],// 当前显示的题库
          currentQuestionsIndex:0,//当前题目索引
          answers:[],//保存用户选择的答案,
          randomTotal:30,//抽取题目数量
          totalTime:0,// 答题使用时间
        }
      },
        computed:{
        ...mapState([
          'study',
          'answerCard',
          'grade',
          'user'
        ])
      },
      mounted(){
        this.questionType = this.$route.params.key;
        setInterval(()=>{
          this.totalTime+=1;
        },60000);
        if(this.study){
          // 是学习的情况下，显示所有的题目
          this.currentQuestions= QuestionBank[this.questionType];
        }else {
          // 从题库中抽取题目
          let totalQuestions =QuestionBank[this.questionType];
          this.currentQuestions = this.randomQuestions(this.randomTotal,totalQuestions);
        }
      },
    methods: {
          //随机抽取题目函数
      randomQuestions(total,questions){
        //total要抽取的题目个数,questions总的题库
          let questionsTotal = questions.length; //题目总量
          let start = Math.floor(Math.random()*(questionsTotal-total));
          let end=start+total;
          return questions.slice(start,end); // 抽取题目
      },//改变答题类型
      changeType(type){
          if(this.currentQuestionsIndex!==this.currentQuestions.length-1){
            this.$dialog.alert({
              message:'当前类型您依然有题目未答，请完成之后再选择其他类型的题目'
            })
          }else {
            this.currentQuestionsIndex=0;
            this.showAnswer=false;
            this.answers=[];
            this.questionType = type;
            if(this.study){
              // 在学习的情况下
              this.currentQuestions= QuestionBank[this.questionType];
            }else {
              // 在练习的情况下
              let totalQuestions =QuestionBank[this.questionType];
              if(this.questionType!=='single'){
                this.randomTotal=10;
              }
              this.currentQuestions=this.randomQuestions(this.randomTotal,totalQuestions);
              // 抽取题目
            }
          }
      },
      //向服务器提交数据
      submit(){
        // 向数据库保存数据
        let data = {
          grade:this.grade,
          time:this.totalTime,
          date:new Date()
        };
        let data1={
          type:this.questionType,
          questions:this.currentQuestions,
          answers: this.answers
        };
        //将本次答题记录存储
        this.$store.commit('set_answerCard',data1);
        this.axios.post(baseUrl.serverUrl+'/user/answer?id='+this.user.id,{content:JSON.stringify(data)}).then(res=>{
          if(res.data.status==1){
            this.$dialog.alert({
              message:'调查提交成功,谢谢您的配合'
            });
            this.$router.push(`/tip`);
          }else {
            this.$dialog.alert({
              message:'提交失败请重试'
            })
          }
        })
      },
      //下一题
      next(){
        if(this.study){
          // 学习
          if(this.currentQuestionsIndex==this.currentQuestions.length-1){
            //最后一题
            this.$dialog.alert({
              message:'当前类型题目已全部测试完毕，请选择其他类型题目测试'
            })
          }else{
            //不是最后一题
            if(!this.answers[this.currentQuestionsIndex]){
              this.$dialog.alert({
                message:'请您对当前题进行作答，然后进行下一题'
              })
            }else {
              this.currentQuestionsIndex++;
              this.showAnswer=false;
            }
          }
        }else {
          // 测试
          if(this.currentQuestionsIndex==this.currentQuestions.length-1){
            //最后一题,存储答题卡
             let data={
                type:this.questionType,
                questions:this.currentQuestions,
                answers: this.answers
             };
            //将本次答题记录存储
            this.$store.commit('set_answerCard',data);
            if(this.type=='gap'){
              this.$dialog.alert({
                message:'当前类型题目已全部测试完毕'
              })
            }else {
              this.$dialog.alert({
                message:'当前类型题目已全部测试完毕，请选择其他类型题目测试'
              })
            }

          }else {
            // 不是最后一题,计算当前获得的成绩
            let userAnswer='',answer='';
            if(this.questionType!=='gap'){
              this.answers[this.currentQuestionsIndex].forEach(val=>{
                val=val.trim();
                userAnswer+=val.slice(0,1);
              });
            }else {
              userAnswer= this.answers[this.currentQuestionsIndex];
            }
            this.currentQuestions[this.currentQuestionsIndex].answers.forEach(val=>{
              answer+=val;
            });
            if(userAnswer==answer){
              this.$store.commit('set_grade',2);
            }
            this.currentQuestionsIndex++;
            this.showAnswer=false;
          }
        }

      }
    }
    }
</script>

<style scoped>

</style>
